#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>

int chooseSpi() {
  FILE *p;
  char line[500];
  unsigned char map[8192];
  int ret, sanity;
  struct timeval tv;

  memset(map, 0, 8192);
  memset(map, 0xff, 25);	/* 0-0x1ff for automatic stuff */
  // p = popen("cat ipsec-spi-out", "r");
  p = popen("/usr/sbin/ipsec spi", "r");
  assert(p);
  while(fgets(line, 500, p)) {
    char *hex;
    unsigned long spi;
    
    line[499] = 0;
    hex = strstr(line, "0x");
    if(!hex)
      continue;
    if(hex - line > 6)
      continue;
    spi = strtoul(hex, NULL, 16);
    if(spi < 65536)
      map[spi >> 3] |= 1 << (spi & 0x7);
    fprintf(stderr, "got spi %lx\n", spi);
  }
  gettimeofday(&tv, NULL);
  srand(tv.tv_sec ^ tv.tv_usec ^ getpid());
  sanity = 0;
  do {
    ret = rand() & 0xffff;
    sanity++;
  } while(sanity < 1000 && map[ret >> 3] & 1 << (ret & 0x7));
  fprintf(stderr, "returning %x after %d\n", ret, sanity);
  return ret;
}
